package com.jxud.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;
@Component
@RequiredArgsConstructor   // Lombok 注解，自动生成构造函数
public class HttpUtil {

    private final WebClient webClient;

    private static final Duration TIMEOUT = Duration.ofSeconds(10); // 超时时间

    /**
     * 发送 GET 请求，返回字符串
     */
    public String get(String url) {
        return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(TIMEOUT)
                .onErrorResume(throwable -> Mono.just("请求失败: " + throwable.getMessage()))
                .block(); // 同步阻塞，适合普通业务
    }

    /**
     * 发送 POST 请求（JSON 数据）
     */
    public String post(String url, Object requestBody) {
        return webClient.post()
                .uri(url)
                .header("Content-Type", "application/json;charset=UTF-8") // ✅ 手动设置
                // 或者更推荐：使用 contentType()
                .contentType(MediaType.APPLICATION_JSON) // 等价于上面，且自动带 charset=UTF-8
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(TIMEOUT)
                .onErrorResume(throwable -> Mono.just("POST 请求失败: " + throwable.getMessage()))
                .block();
    }
}
